﻿/**************************************************************************
创建时间:	2020/5/13
作	  者:	张存
邮 	  箱:	zhangcunliang@126.com

Copyright (c) zhcun.cn

描	述： 实现普通的增删查改页面
记	录：
***************************************************************************/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ZhCun.Utils;
using ZhCun.Win.ExtendSearch;

namespace ZhCun.Win
{
    public partial class FrmCrud : FrmBase
    {
        public FrmCrud()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 是否启用分页
        /// </summary>
        public virtual bool IsPager { get; } = true;
        /// <summary>
        /// 每页显示行的分组列表，默认: 50,100,200
        /// </summary>
        public int[] OnePages { get; protected set; } = { 50, 100, 200 };
        /// <summary>
        /// 创建新增窗体的方法（必须重写）
        /// </summary>
        /// <returns></returns>
        protected virtual FrmBaseEdit CreateAddForm()
        {
            throw new NotImplementedException($"未实现 {nameof(CreateAddForm)}");
        }
        /// <summary>
        /// 创建更新窗体的方法（如果 CreateAddForm 有实现，且编辑框一致则不用重写，否则必需重写）
        /// </summary>
        protected virtual FrmBaseEdit CreateEditForm()
        {
            return CreateAddForm();
        }
        /// <summary>
        /// 获取数据源的方法 （必须重写）
        /// </summary>
        protected virtual DataTable GetDataSource(int pageNo, int pageSize, string searchVal, out int rowCount)
        {
            throw new NotImplementedException($"未实现 {nameof(GetDataSource)}");
        }
        /// <summary>
        /// 新增处理 （必须重写）
        /// </summary>
        protected virtual ApiResult<string> AddSaveHandle(object m)
        {
            throw new NotImplementedException($"未实现 {nameof(AddSaveHandle)}");
        }
        /// <summary>
        /// 更新处理 （必须重写）
        /// </summary>
        protected virtual ApiResult<string> EditSaveHandle(object m)
        {
            throw new NotImplementedException($"未实现 {nameof(EditSaveHandle)}");
        }
        /// <summary>
        /// 删除处理 （必须重写）
        /// </summary>
        protected virtual ApiResult DelHandle(object model)
        {
            throw new NotImplementedException($"未实现 {nameof(DelHandle)}");
        }
        /// <summary>
        /// 创建保存实体对象 （必须重写）
        /// </summary>
        public virtual object CreateSaveModel()
        {
            throw new NotImplementedException($"未实现 {nameof(CreateSaveModel)}");
        }
        /// <summary>
        /// 高级搜索点击
        /// </summary>
        protected virtual void AdSearch_Click(object sender, EventArgs e)
        {
            ShowMessage("未实现高级搜索");
        }
        /// <summary>
        /// DataGridView  选中行 （必须重写）
        /// </summary>
        public virtual object GetGridSelected()
        {
            return dgv.GetSelectedItemData();
        }
        /// <summary>
        /// 窗体加载后的事件
        /// </summary>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
        }
        /// <summary>
        /// 绑定数据源
        /// </summary>
        protected void BindDataSource()
        {
            //分页查询
            var dt = GetDataSource(1, ucPageNav.OnePageCount, tsTxtSearch.Text, out int rowCount);
            dgv.DataSource = dt;
            ucPageNav.InitiControl(rowCount);
        }

        #region 控件事件

        /// <summary>
        /// 注册控件的事件
        /// </summary>
        void RegisterEvent()
        {
            tsbtnExit.Click += BtnExit_Click;
            tsBtnAdd.Click += BtnAdd_Click;
            tsBtnCopyAdd.Click += BtnCopyAdd_Click;
            tsBtnEdit.Click += BtnEdit_Click;
            tsBtnDelete.Click += BtnDelete_Click;
            tsBtnSearch.Click += BtnSearch_Click;
            tsAdSearch.Click += AdSearch_Click;
            tsTxtSearch.KeyDown += TxtSearch_KeyDown;
            ucPageNav.PageChangedEvent += Page_PageChangedEvent;
        }

        private void BtnExit_Click(object sender, EventArgs e)
        {
            Close();
        }

        void ShowAdd(bool isCopyAdd = false)
        {
            EditFormArgs arg = new EditFormArgs
            {
                ClearId = true,
                SaveHandle = AddSaveHandle,
                SaveModel = CreateSaveModel()
            };

            if (isCopyAdd)
            {
                arg.SetModel = GetGridSelected();
                if (arg.SetModel == null)
                {
                    ShowMessage("没有选中任何行");
                    return;
                }
            }
            var frm = CreateAddForm();
            frm.Text += " 新增";
            var ret = frm.ShowDialog(arg);
            if (ret)
            {
                ShowMessage(ret.msg);
                BindDataSource();
            }
        }

        private void BtnAdd_Click(object sender, EventArgs e)
        {
            ShowAdd();
        }

        private void BtnCopyAdd_Click(object sender, EventArgs e)
        {
            ShowAdd(true);
        }

        private void BtnEdit_Click(object sender, EventArgs e)
        {
            var selModel = GetGridSelected();
            if (selModel == null)
            {
                ShowMessage("没有选中任何行");
                return;
            }

            var frm = CreateEditForm();
            frm.Text += " 编辑";
            EditFormArgs arg = new EditFormArgs
            {
                SaveHandle = EditSaveHandle,
                SaveModel = CreateSaveModel(),
                SetModel = selModel
            };
            var ret = frm.ShowDialog(arg);
            if (ret)
            {
                ShowMessage(ret.msg);
                BindDataSource();
            }
        }

        private void BtnDelete_Click(object sender, EventArgs e)
        {
            if (!ShowQuestion("确实要删除当前记录吗？", "删除确认"))
            {
                return;
            }
            var vm = GetGridSelected();
            if (vm == null)
            {
                ShowMessage("没有选中任何行");
                return;
            }
            var ret = DelHandle(vm);
            if (ret)
            {
                BindDataSource();
            }
            ShowMessage(ret.msg);
        }
        /// <summary>
        /// 刷新数据源
        /// </summary>
        protected virtual void BtnSearch_Click(object sender, EventArgs e)
        {
            BindDataSource();
        }

        private void TxtSearch_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                BtnSearch_Click(sender, e);
            }
        }

        private void Page_PageChangedEvent(int pageNo, int pageSize, out int rowCount)
        {
            //分页查询
            var dt = GetDataSource(pageNo, pageSize, tsTxtSearch.Text, out rowCount);
            dgv.DataSource = dt;
        }

        #endregion

        private void FrmCrud_Load(object sender, EventArgs e)
        {
            if (!DesignMode)
            {
                RegisterEvent();
                //var cols = GetDgvCloumnInfo();
                //if (cols != null)
                //{
                //    foreach (var col in cols)
                //    {
                //        dgv.Columns.Add(col);
                //    }
                //}
                //else
                //{
                //    //实现增删查改的标准窗体不使用自动初始化,是为了减少查找GridView的开销
                //    GridViewHelper.InitGridView(this, dgv);
                //}
            }
        }
    }
}